package com.stable.spider.ths;

import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.stable.utils.HtmlunitSpider;
import com.stable.vo.spi.req.ThsBasic;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Log4j2
public class ThsBasicSpider {

    /**
     * 从同花顺拿到最关心的公司亮点数据
     *
     * @param code
     * @return http://basic.10jqka.com.cn/603799/
     */
    public ThsBasic getTHSBasicInfo(String code) {
            HtmlunitSpider htmlunitSpider = new HtmlunitSpider();
            HtmlPage htmlPageFromUrl = htmlunitSpider.getHtmlPageFromUrl("http://basic.10jqka.com.cn/" + code);
            HtmlElement body = htmlPageFromUrl.getBody();
            List<HtmlElement> elementsByAttribute = body.getElementsByAttribute("table", "class", "m_table m_table_db");

        List<HtmlElement> elementsByAttribute2 = body.getElementsByAttribute("table", "class", "m_table m_table_db mt10");

            List list = new ArrayList();
            ThsBasic thsBasic = new ThsBasic(code);
            try {
                List<HtmlElement> gsldSpan = elementsByAttribute.get(0).getElementsByAttribute("span", "class", "tip f14 fl core-view-text");
                thsBasic.setGsld(gsldSpan.get(0).asText()); //公司亮点

                List<HtmlElement> sshySpan = elementsByAttribute.get(0).getElementsByAttribute("span", "class", "tip f14");
                thsBasic.setSshy(sshySpan.get(0).asText());//所属申万行业


                List<HtmlElement> td = elementsByAttribute2.get(0).getElementsByAttribute("td", "", "");
                for(int i=0;i<td.size();i++) {
                    if (td.get(i).asText().contains("最新解禁")) {
                        thsBasic.setZxjj(td.get(i).asText());//最新解禁
                    }
                    if (td.get(i).asText().contains("质押股份占A股总股本比")) {
                        thsBasic.setZybl(td.get(i).asText().split("%")[0]+"%");//已经质押股份占A股总股本比
                    }
                }
                return thsBasic;
            } catch (RuntimeException e) {
                log.error("股票代码：{} 获取基本数据失败 getTHSBasicInfo：", code, e);
                return thsBasic;
            }
    }

    public static void main(String[] args) {
        //ThsBasicSpider.getTHSBasicInfo("300003");
    }
}
